package edu.neu.cloud_factory.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.neu.cloud_factory.entity.po.Bid;
import edu.neu.cloud_factory.entity.po.Order;
import edu.neu.cloud_factory.entity.po.Schedule;
import edu.neu.cloud_factory.entity.po.User;
import edu.neu.cloud_factory.service.*;
import edu.neu.cloud_factory.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author halozhy
 * @since 2021-07-15
 */
@RestController
@RequestMapping("/api/order")
public class OrderController {
    @Autowired
    OrderService orderService;

    @Autowired
    ProductService productService;

    @Autowired
    UserService userService;

    @Autowired
    BidService bidService;

    @Autowired
    ScheduleService scheduleService;


//    @PostMapping("/list")
//    public JSONObject list(@RequestBody String CONTENT) {
//        JSONObject j = JSONObject.parseObject(CONTENT);
//        return orderService.listOrder(
//                j.getInteger("page"),
//                j.getInteger("limit"),
//                j.getString("id"),
//                j.getString("receiver_name"),
//                j.getString("receiver_address")
//        );
//    }

    @PostMapping("/list_dealer")
    public JSONObject listDealer(@RequestBody String CONTENT) {
        JSONObject j = JSONObject.parseObject(CONTENT);
        return orderService.listOrderDealer(
                j.getInteger("page"),
                j.getInteger("limit"),
                j.getLong("user_id"),
                j.getString("id"),
                j.getString("receiver_name"),
                j.getString("product_name")
        );
    }

    @PostMapping("/list_fac_can_bid")
    public JSONObject listFacCanBid(@RequestBody String CONTENT) {
        JSONObject j = JSONObject.parseObject(CONTENT);
        return orderService.listOrderFacCanBid(
                j.getInteger("page"),
                j.getInteger("limit"),
                j.getLong("user_id"),
                j.getString("id"),
                j.getString("receiver_name"),
                j.getString("product_name")
        );
    }

    @PostMapping("/list_fac")
    public JSONObject listFac(@RequestBody String CONTENT) {
        JSONObject j = JSONObject.parseObject(CONTENT);
        return orderService.listOrderFacAlreadyBid(
                j.getInteger("page"),
                j.getInteger("limit"),
                j.getLong("user_id"),
                j.getString("id"),
                j.getString("receiver_name"),
                j.getString("product_name")
        );
    }

    @PostMapping("/list_su_admin")
    public JSONObject listSuAdmin(@RequestBody String CONTENT) {
        JSONObject j = JSONObject.parseObject(CONTENT);
        return orderService.listOrderSuAdmin(
                j.getInteger("page"),
                j.getInteger("limit"),
                j.getString("id"),
                j.getString("receiver_name"),
                j.getString("product_name")
        );
    }

    @PostMapping("/add")
    public int add(@RequestBody String CONTENT) {
        // TODO 优化鉴权
        JSONObject j = JSONObject.parseObject(CONTENT);
        if (!Utils.checkEmpty(j, Arrays.asList("num", "receiver_name", "receiver_tel", "receiver_addr", "deliver_date", "bid_end_date", "product_id", "user_id"))) {
            return -2; // 存在空字段
        }
        Order order = new Order();
        long productId = j.getLong("product_id");
        if (productService.getById(productId) == null) {
            return -1; // 产品id错误
        }


        User u = userService.getById(j.getLong("user_id"));
        if (u == null) {
            return -3; // 用户id不正确
        }

        order.setOState("已发布");
        order.setONum(j.getLong("num"));
        order.setOReceiverName(j.getString("receiver_name"));
        order.setOReceiverTel(j.getString("receiver_tel"));
        order.setOReceiverAddr(j.getString("receiver_addr"));
        LocalDate deliver_date = Utils.parseToLocalDate(j.getString("deliver_date"));
        LocalDate bid_end_date = Utils.parseToLocalDate(j.getString("bid_end_date"));
        LocalDate now = LocalDate.now();
        if (deliver_date.isBefore(now)|| bid_end_date.isBefore(now)){
            return -5; // 投标或收货截止日期必须晚于当前日期
        }
        if (deliver_date.isBefore(bid_end_date)){
            return -6; // 收货截止日期必须晚于投标截止日期
        }
        order.setODeliverDate(deliver_date);
        order.setOBidEndDate(bid_end_date);
        order.setOProductId(j.getLong("product_id"));
        order.setOUserId(j.getLong("user_id"));

        // 验证传入的user_id必须为经销商
        if (u.getUType().equals("经销商")) {
            orderService.save(order);
            return 0;
        } else {
            return -4; // 权限错误
        }
    }

    @GetMapping("/can_update")
    public int canUpdate(int oId) {
        // 这个不按照最早的任务书要求来做，订单能够修改的字段为
        // 收货人信息，(以及可以把收货截止时间或者投标截止时间往后修改)
        // 订单能够修改的条件为：订单的状态不是已发货或者未中标
        Order order = orderService.getById(oId);
        if (order != null) {
            if (!order.getOState().equals("已发货") || !order.getOState().equals("未中标")) {
                return 0;
            } else {
                return -1; // 提示：此状态不可修改
            }

        }
        return -2; // 找不到
    }


    @PostMapping("/update")
    public int update(@RequestBody String CONTENT) {
        // TODO 优化鉴权
        // 暂定能够修改的就只有收货人信息
        JSONObject j = JSONObject.parseObject(CONTENT);
        if (!Utils.checkEmpty(j, Arrays.asList("id", "receiver_name", "receiver_tel", "receiver_addr", "user_id"))) {
            return -2; // 存在空字段
        }
        User u = userService.getById(j.getLong("user_id"));
        if (u == null) {
            return -5; // 用户id不存在
        }
        Order order = orderService.getById(j.getInteger("id"));
        if (order == null) {
            return -1; // 无此订单
        }
        if (!order.getOState().equals("已发货") || !order.getOState().equals("未中标")) {
            if (!order.getOUserId().equals(u.getUId()) || !u.getUType().equals("经销商")) {
                // 不是这个订单的创建者 或者 不是经销商
                return -6; // 权限错误
            }
            order.setOReceiverName(j.getString("receiver_name"));
            order.setOReceiverTel(j.getString("receiver_tel"));
            order.setOReceiverAddr(j.getString("receiver_addr"));
            orderService.updateById(order);
            return 0;
        } else {
            return -3; // 提示：此状态不可修改
        }
    }

    @GetMapping("/delete")
    public int delete(int dId) {
        // 这个也对旧版的任务书做一些修改，只能删除未中标的订单
        // TODO 鉴权
        Order order = orderService.getById(dId);
        if (order == null) {
            return -2; // 无此订单
        }
        if (order.getOState().equals("未中标")) {
            orderService.removeById(order);
            return 0;
        } else {
            return -1; // 此订单此状态不可删除
        }
    }

    @GetMapping("/finish")
    public int finish (long orderId){
        Order order = orderService.getById(orderId);
        if(order == null){
            return -2;
        }
        // order -> bid -> schedule
        // 检查此订单下是否有排产，有，直接把状态改变即可
        QueryWrapper<Bid> bidQueryWrapper = new QueryWrapper<>();
        bidQueryWrapper.eq("b_order_id", order.getOId());
        bidQueryWrapper.eq("b_state", "已中标");
        Bid bid = bidService.getOne(bidQueryWrapper); // 应当只有一个是中标的
        QueryWrapper<Schedule> scheduleQueryWrapper = new QueryWrapper<>();
        scheduleQueryWrapper.eq("s_bid_id", bid.getBId());
        List<Schedule> scheduleList = scheduleService.list(scheduleQueryWrapper);
        if (scheduleList.size() == 0){
            // 无 -1
            return -1;
        }
        order.setOState("未发货");
        orderService.updateById(order);
        return 0;
    }

    @GetMapping("/deliver")
    public int deliver (long orderId){
        Order order = orderService.getById(orderId);
        if(order == null){
            return -2;
        }
        // 检查此订单是否为 未发货 状态
        if (order.getOState().equals("未发货")){
            order.setOState("已发货");
            orderService.updateById(order);
            return 0;
        }
        return -1;
    }

    @GetMapping("/recv")
    public int recv (long orderId){
        Order order = orderService.getById(orderId);
        if(order == null){
            return -2;
        }
        // 检查此订单是否为 已发货 状态
        if (order.getOState().equals("已发货")){
            order.setOState("已完成");
            orderService.updateById(order);
            return 0;
        }
        return -1;
    }
}

